mod catcher;
mod com;
mod data_store;
mod downloader;
mod myerror;
mod remove_duplicated;
mod url;
use crate::catcher::Catcher;
use crate::com::Com;
use crate::remove_duplicated::Remover;
use data_store::DataStore;
use std::env::{args, self};
use std::path::PathBuf;
use std::thread;
use std::time::Duration;
use log::*;
const SLEEP_TIME: u64 = 5;
fn read_from_user() {
    let mut catcher = Catcher::new(0);
    loop {
        let com = Com::new();
        if let Err(r) = com {
            println!("ERROR: \x1b[0;91m{:#?}\x1b[0m", r);
            continue;
        }
        let result = catcher.run_com(com.unwrap());
        if let Err(r) = result {
            println!("ERROR: \x1b[0;91m{:#?}\x1b[0m", r);
            continue;
        }
    }
}
fn read_from_file(file_name: &str) {
    let path = PathBuf::from(file_name);
    env::set_var("RUST_LOG", "info");
    simple_logger::init_with_env().unwrap();
    info!("logger inited");
    loop {
        info!("started to read");
        let mut data_store = DataStore::new(&path).unwrap();
        let update_data = data_store.update().unwrap();
        info!("update_data: {:?}", update_data);
        let remover = Remover::new(update_data.clone(), data_store.config.articles_ids.clone());
        data_store.config.articles_ids = update_data;
        data_store.save(&path).unwrap();
        let need_update = remover.start();
        //errors will happen when downloading
        let download_result = data_store.start_download(need_update);
        if let Err(er) = download_result {
            error!("download errors:{:#?}", er);
        }
        info!("sleep for {} hours", SLEEP_TIME);
        thread::sleep(Duration::from_secs(SLEEP_TIME * 60 * 60));
    }
}
fn main() {
    let arg: Vec<String> = args().collect();
    match arg.get(1) {
        Some(a) => read_from_file(a),
        None => read_from_user(),
    }
}
